<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/8/18
 * Time: 11:15
 */

namespace app\logic\cron;


use app\common\lib\Common;
use app\common\lib\Guzzle;
use app\common\lib\GuzzleNew;
use app\common\lib\TencentCos;
use app\exception\IndexException;
use app\logic\BaseLogic;
use app\model\bingtian\BingTianNovelModel;
use app\model\novel\NovelChapterModel;
use app\model\novel\NovelChapterPartModel;
use app\model\novel\NovelSpreadModel;
use app\model\novel\NovelSpreadUnderWaterModel;
use support\Db;

class BingTianLogic extends BaseLogic
{
    protected $apiId = 'bingtian_xianyu';
    protected $singKey = 'Aa9Lnh82K-w0Mq_bC=E)';
    protected static $instance;

    protected $insertTaskDatas;

    public function __construct()
    {
        parent::__construct();
    }

    public static function getInstance()
    {
//        if (is_object(self::$instance)) {
//            return self::$instance;
//        }

        return  new self();
    }

    protected function sign($param)
    {
        ksort($param);
        $arr = [];
        foreach($param as $key=>$val){
            $arr[] = ($key.'='.$val);
        }
        $param['sign'] = md5($this->singKey.implode('&',$arr));

        return $param;
    }

    public function getNovelList()
    {
        //获取分类
        $param = [
            'api_id'=>$this->apiId,
            'timestamp'=>time(),
        ];
        $param = $this->sign($param);
        $path = 'BookAmount/getCategoryList?'.http_build_query($param);
        $result2 = Common::curlApi('https://read-douyin-api.shruisong.net/'.$path);
        $tagsMap = [];
        if(!empty($result2['data']['list'])){
            $tagsMap = array_column($result2['data']['list'],'category_name','category_id');
        }

        $page=1;
        $size = 200;
        while (true){
            $param = [
                'page'=>$page,
                'page_size'=>$size,
                'api_id'=>$this->apiId,
                'timestamp'=>time(),
            ];
            $param = $this->sign($param);
            $path = 'BookAmount/getBookList?'.http_build_query($param);
            $result = (new GuzzleNew())->get('https://read-douyin-api.shruisong.net/',$path);
            if(!empty($result['data']['list'])){
                $data = $result['data']['list'];
                $bookIds = array_column($data,'book_id');
                $where = [['book_id','in',$bookIds]];
                $novelDatas = BingTianNovelModel::getInstance()->getWhere($where)->get()->toArray();
                $novelMap = array_column($novelDatas,null,'book_id');

                $inserts = [];
                foreach($data as $val){
                    if(!empty($novelMap[$val['book_id']])){
                        if(empty($novelMap[$val['book_id']]['chapter_content'])){
                            //获取免费章节内容
                            $param = [
                                'book_id'=>$val['book_id'],
                                'api_id'=>$this->apiId,
                                'timestamp'=>time(),
                            ];
                            $param = $this->sign($param);
                            $path = 'BookAmount/getBookFreeChapter?'.http_build_query($param);
                            $chapterContent = Common::curlApi('https://read-douyin-api.shruisong.net/'.$path);
                            //var_dump($chapterContent);
                            $chapterContent = is_string($chapterContent) ? $chapterContent : '';

                            BingTianNovelModel::getInstance()->getWhere(['book_id'=>$val['book_id']])->update(['chapter_content'=>$chapterContent]);
                        }else{
                            $chapterContent = $novelMap[$val['book_id']]['chapter_content'];
                        }

                        $first = $novelMap[$val['book_id']];
                        //更新水上的小说内容
                        $novels = NovelSpreadModel::getInstance()->getWhere([['business_id','in',[12,13,100]],'title'=>$first['name'],'isdel'=>0])->get();
                        foreach ($novels as $novel){
                            if($novel['main_image']!=$first['cover_url']){
                                $novel->main_image = $first['cover_url'];
                            }
                            if(empty($novel['labels'])){
                                $novel->labels = $first['tags'];
                            }
                            if(empty($novel['desc'])){
                                $novel->desc = $first['describe'];
                            }
                            if(empty($novel['author'])){
                                $novel->author = $first['author'];
                            }
                            if(empty($novel['book_id'])){
                                $novel->book_id = $first['book_id'];
                            }
                            $novel->save();

                            $originalContent = NovelChapterModel::getInstance()->getWhere(['novel_sn'=>$novel['novel_sn'],'isdel'=>0])->value('original_content');
                            if(empty($originalContent) && !empty($chapterContent)){
                                NovelChapterModel::getInstance()->insertGetId(
                                    [
                                        'novel_sn'=>$novel['novel_sn'],
                                        'number'=>1,
                                        'name'=>'第1章',
                                        'original_content'=>$chapterContent,
                                        'status'=>1,
                                    ]
                                );
                            }
                        }
                    }else{
                        //上传封面图
                        $mainImage = '';
                        $mainImageFileName = substr(md5(uniqid().time()),-26).'.jpg';
                        try{
                            $res = TencentCos::getInstance()->uploadLocalFile($val['cover_url'],'bingtian/novel',$mainImageFileName);
                            if(isset($res['Location'])){
                                $mainImage = 'https://'.$res['Location'];
                            }
                        }catch (\Exception $e){}

                        //获取免费章节内容
                        $param = [
                            'book_id'=>$val['book_id'],
                            'api_id'=>$this->apiId,
                            'timestamp'=>time(),
                        ];
                        $param = $this->sign($param);
                        $path = 'BookAmount/getBookFreeChapter?'.http_build_query($param);
                        $chapterContent = Common::curlApi('https://read-douyin-api.shruisong.net/'.$path);
                        $chapterContent = is_string($chapterContent) ? $chapterContent : '';
                        //var_dump($chapterContent);

                        $inserts[] = [
                            'book_id'=>$val['book_id'],
                            'name'=>$val['name'],
                            'book_status'=>$val['book_status'],
                            'author'=>$val['author'],
                            'cover_url'=>$mainImage,
                            'category_id'=>$val['category_id'],
                            'describe'=>$val['describe'],
                            'chapter_content'=>$chapterContent,
                            'tags'=>$tagsMap[$val['category_id']]??'',
                        ];
                    }

                    usleep(20000);
                }

                $inserts && BingTianNovelModel::getInstance()->insert($inserts);
            }else{
                break;
            }
            //break;
            $page++;
            sleep(1);
        }


        return ['success'];
    }
}